<?php

namespace app\system\controller;

use app\common\controller\Excel;
use app\common\lib\Redis;
use app\common\model\Amount;
use app\common\model\Rec;
use think\Db;
use think\Exception;
use app\common\model\Account as A;
use app\common\model\Logs;

class Account extends Common
{
    protected $table = 'member_account', $name = '账户流水';

    function select($count = false)
    {
        $type = input('type');
        $where['t.is_del'] = 0;
        switch ($type) {
            case 1:
                $where['t.intro'] = ['in', ['转出', '转入']];
                break;
            case 2:
                $where['t.intro'] = ['in', ['兑换分红股', '兑换奖金']];
                break;
            case 3:
                $where['t.intro'] = '后台充值';
                break;
            case 4:
                $where['t.category'] = 21;
                break;
            case 5:
                $where['t.intro'] = ['in', ['直推奖','间推奖','团长奖励','续费间推','直推股息','团队股息','推广奖']];
                break;

            default:
                $where['t.type'] = $type;
                break;
        }

        $type_t = input('type_t');
        if ($type_t) {
            $where['t.type'] = $type_t;
        }

        $category = input('category');
        if ($category) {
            $where['t.intro'] = $category;
        }
        $intro = input('intro');
        if ($intro) {
            $where['t.intro'] = $intro;
        }
        $keyword = input('keyword');
        if ($keyword) {
            $map['name|code'] = $keyword;
            $is = Db::name('user')->where($map)->value('id');
            $where['t.uid'] = $is;
        }

        if (input('start')) {
            $start=str_replace('+',' ',input('start'));
            $value = explode(' - ', $start);
            $where['t.create_time'] = array('between', '' . strtotime($value[0]) . ',' . strtotime($value[1]) . '');
        }
        if($count){
            return Db::name($this->table . ' t')->where($where)->count('id');
        }else{
            return db($this->table . ' t')
                ->join('user m', 'm.id=t.uid', 'left')
                ->join('user m2', 'm2.id=t.source', 'left')
                ->field('t.*,m.code,m.name,m2.name as r_nickname,m2.code as r_code')
                ->where($where)->order('t.id desc');
        }

    }

    function index()
    {
        if(input('type') == 4){
            $list = db('fin_allocation')->paginate(20, false, ['query' => request()->get()]);
            $this->assign('list',$list);
            return $this->fetch('bonus');
        }
        $count = $this->select(true);
        $list = $this->select()->paginate(20, $count, ['query' => request()->get()]);
        $this->assign('list', $list);
        $this->assign('category', [
            1 => '直推奖', 2 => '间推奖', 3 => '级别奖励', 4 => '服务中心奖',
            5 => '代理奖', 6 => '总监分红'
        ]);
        $this->assign('count',$count);
        return $this->fetch();
    }

    public function recharge(){
        $keyword = input('keyword');
        if ($keyword) {
            $where['nickname|code'] = $keyword;
        }
        if (input('start')) {
            $value = explode(' - ', input('start'));
            $where['t.create_time'] = array('between', '' . strtotime($value[0]) . ',' . strtotime($value[1]) . '');
        }
        $list = Db::name('member_recharge')->where($where)->order('create_time','desc')
            ->paginate(20, false, ['query' => request()->get()]);
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function recharge_state($id, $key, $val)
    {
        Db::startTrans();
        try {
            //通过审核
            $info = Db::name('member_recharge')->find($id);
            if($info['state']!==1){
                return json(['status' => 1, 'message' => '已完成审核']);
            }
            if ($val == 2) {
                $infos = json_encode(['id' => $info['uid'], 'amount' => $info['total'], 'type' => 'group_bonus', 'fx' => '+']);
                // Redis::Instance()->lpush('balance_grant', $infos);
               // Db::name('member')->where('id', $info['uid'])->inc('group_bonus',$info['total'])->update();
                $data = A::create_Inc($info['uid'], $info['total']*config('usdt_pro'), 'coins', '充值', '', '+','','');

            }
            Db::name('member_recharge')->where('id', $id)->update(['update_time' => time(), $key => $val]);
            Db::commit();
            return json(['status' => 1, 'message' => '已审核']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => -1, 'message' => $e->getMessage()]);
        }

    }


    function add($id = '')
    {
        if ($id) {
            $info = db($this->table)->find($id);
            $this->assign('info', $info);

            $images = db($this->table_images)->where(['upid' => $id])->select();
            $this->assign('images', $images);
        }

        return $this->fetch();
    }

    function add_bonus()
    {
        $start_time = db('fin_allocation')->max('end_time');
        $this->assign('start_time', $start_time);
        return $this->fetch();
    }

    public function statistics()
    {
        $level = db('level_think')->where('bonus', '>', 0)->order('id desc')->find();
        $result['member_count'] = db('member')->where('think_id', $level['id'])->count();

        $result['start_time'] = db('fin_allocation')->max('end_time');//获取上一次分红时间
        $result['end_time'] = strtotime(input('get.end_time'));//获取所选时间
        $map = ['create_time' => ['between', [$result['start_time'], $result['end_time']]], 'type' => 1];//设置查询条件
        $result['total_amount'] = db('member_amount')->where($map)->sum('amount');//查询总收益
        $result['allocation_amount'] = $result['total_amount'] * $level['bonus'];//设置可以分配数额
        $result['per_amount'] = $result['member_count'] != 0 ? $result['allocation_amount'] / $result['member_count'] : 0;//计算平均分配数额
        $result['should_amount'] = $result['allocation_amount'];//设置应分配数额
        return $result;//返回查询到数据
    }

    /**
     * 原点 2020年8月21日11:21:12 发放董事分红
     *
     * @return \think\response\Json
     */
    public function dividends()
    {
        Db::startTrans();
        try {
            $param = input("post.");
            $param['code'] = date('YmdHis', time()) . mt_rand(100, 999);
            $param['start_time'] = strtotime(input('post.start_time'));
            $param['end_time'] = strtotime(input('post.end_time'));
            $param['create_time'] = time();
            $param['create_emp_id'] = $this->admin['id'];
            $param['create_emp_name'] = $this->admin['AdminName'];
            $res = db('fin_allocation')->insert($param);
            if (!$res) {
                Db::rollback();
                return json(['code' => -1, 'msg' => '发放失败']);
            }
            $level = db('level_think')->where('bonus', '>', 0)->order('id desc')->find();
            $member = db('member')->where('think_id', $level['id'])->select();

            if ($param['allocation_amount'] > 0 && !empty($member)) {

                $sum_amount = 0;
                foreach ($member as $key => $value) {
                    //1.获取我的团队
                    $teams_id = db('member_rec')->where('member_id', $value['id'])->column('new_member_id');
                    $teams_id[] = $value['id'];//需包含自己的业绩
                    //2.查询团队总业绩
                    $member[$key]['teams_amount'] = Amount::get_amount(['type' => 1, 'uid' => ['in', $teams_id]]);
                    //3.累加团队总业绩
                    $sum_amount += $member[$key]['teams_amount'];

                }
                foreach ($member as $key => $value) {
                    //4.计算分红的金额
                    $amount = round($value['teams_amount'] / $sum_amount * $param['allocation_amount'],2);
                    if ($amount && $amount > 0) {
                        //5.发放
                        A::agent_add($value['id'], $amount, '董事分红', 0, '+', 12);
                    }
                }

                $msg = '已发放';
            } else {
                $msg = '已发放，但董事分红为0或没有董事会员';
            }
            Logs::add($this->admin['id'], $this->admin['AdminName'], '发放了董事分红');
            Db::commit();
            return json(['code' => 1, 'msg' => $msg]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => -1, 'msg' => '', 'result' => $e->getMessage()]);
        }
    }

    function save($id = '')
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                //数据
                $data = input('post.');
                $data['update_time'] = time();

                //图片数据
                unset($data['imgs']);
                $images = input('imgs/a');

                if ($id == '') {
                    //新增
                    $data['create_time'] = time();
                    $res = db($this->table)->insertGetId($data);
                    $id = $res;
                    $action = '添加';
                } else {
                    //修改
                    $res = db($this->table)->where(['id' => $id])->update($data);
                    $action = '修改';
                }
                if ($res) {
                    //保存图片
                    $res = $this->saveImages($id, $images);
                    if ($res['status'] != '1') {
                        Db::rollback();
                        return return_message('0', '保存失败', '4');
                    }

                    //整体成功
                    Db::commit();
                    action('common/Logs/addLog', ['管理员[' . $this->admin['AdminName'] . ']' . $action . '了' . $this->name . '，' . $this->name . 'ID[' . $id . ']']);
                    return return_message('1', '保存成功');
                } else {
                    Db::rollback();
                    return return_message('0', '保存失败', '3');
                }
            } catch (Exception $e) {
                Db::rollback();
                return return_message('0', '保存失败', '2');
            }
        } else {
            return return_message('0', '保存失败', '1');
        }
    }

    /**
     * 多图片保存
     * @param $id
     * @param array $images
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function saveImages($id, array $images)
    {
        if (!empty($images)) {
            Db::startTrans();
            try {
                //删除旧图
                db($this->table_images)->where(['upid' => $id])->delete();

                //上传新图
                $datas = [];
                foreach ($images as $k => $v) {
                    $datas[] = ['upid' => $id, 'img' => $v];
                }
                db($this->table_images)->insertAll($datas);
                Db::commit();
                return return_message('1', '图片保存成功');
            } catch (Exception $e) {
                Db::rollback();
                return return_message('0', '图片保存失败');
            }
        } else {
            return return_message('1', '图片保存成功');
        }
    }

    function state($id, $key, $val)
    {
        return $this->editState($this->table, $id, $key, $val);
    }

    function value($id, $key, $val)
    {
        return $this->editValue($this->table, $id, $key, $val);
    }

    function export()
    {
        $param = input('param.');
        $type = $param['type'];
        $where['t.is_del'] = 0;
        $map = [
            ['title' => '用户姓名', 'key' => 'nickname'],
            ['title' => '用户编号', 'key' => 'code'],
            ['title' => '时间', 'key' => 'create_time'],
            ['title' => '金额', 'key' => 'amount'],
            ['title' => '账户类型', 'key' => 'type'],
            ['title' => '说明', 'key' => 'intro'],
            ['title' => '来源会员姓名', 'key' => 'r_nickname'],
            ['title' => '来源会员编号', 'key' => 'r_code'],
            ['title' => '备注', 'key' => 'msg'],
        ];
        switch ($type) {
            case 1:
                $title = '转账记录';
                break;
            case 2:
                $title = '转换记录';
                break;
            case 3:
                $title = '充值记录';
                break;
            case 4:
                $title = '董事分红';
                break;
            case 5:
                $title = '奖金明细';
                break;

            default:
                $title = get_pay_way($type);
                break;
        }
        $data = $this->select()->select();
        foreach ($data as &$v) {
            $v['amount'] = $v['fx'] . $v['amount'];
            $v['type'] = get_pay_way($v['type']);
            $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
           $excel = new Excel();
        $excel->export($title . " - " . date('YmdHis'), $map, $data);
    }

    function sum()
    {
        $where = [];
        if (input('Code')) $where['m.code'] = ['like', '%' . input('Code') . '%'];
        if (input('start')) {
            $value = explode(' - ', input('start'));
            $where['t.create_time'] = array('between', '' . strtotime($value[0]) . ',' . strtotime($value[1]) . '');
        }
        $list = db('account_sum t')
            ->join('member m', 'm.id=t.member_id', 'left')
            ->field('t.*,m.code')
            ->where($where)->order('t.member_id,t.create_date')->paginate(20, false, ['query' => request()->get()]);
        $this->assign('list', $list);
        $sum = db('account_sum t')
        ->join('member m', 'm.id=t.member_id', 'left')    
        ->where($where)
            ->field('sum(sum1) as sum1,
            sum(sum2) as sum2,
            sum(sum3) as sum3,
            sum(sum4) as sum4,
            sum(sum5) as sum5,
            sum(sum6) as sum6,
           
            sum(amount_sum) as amount_sum')->find();
        $this->assign('sum', $sum);
        return $this->fetch();
    }
    public function integral_list()
    {
        $where = [];
        if (input('Code')) $where['m.code'] = ['like', '%' . input('Code') . '%'];
        if (input('start')) {
            $value = explode(' - ', input('start'));
            $where['t.create_time'] = array('between', '' . strtotime($value[0]) . ',' . strtotime($value[1]) . '');
        }
        $list = db('release')->alias('t')
            ->join('member m', 't.member_id=m.id', 'left')
            ->field('t.*,m.code,m.nickname')
            ->where($where)->order('t.id desc')->paginate(20, false, ['query' => request()->get()]);
        $this->assign('list', $list);
        return $this->fetch();

    }

}